package com.villaday.idf.activity;

import android.content.Intent;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.villaday.idf.R;
import com.villaday.idf.adapter.CommissionSettingAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.ConfirmDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.SettingGroupDialog;
import com.villaday.idf.custom.UpdateGroupDialog;
import com.villaday.idf.model.AddGroupEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.SaveGroup;
import com.villaday.idf.model.allVipMembersEntity;
import com.villaday.idf.model.feedbackEntity;
import com.villaday.idf.model.vipsGroupsEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.OkHttpUtil.OnDataListener;
import com.villaday.idf.util.PreferencesUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 分庸设置
 */
public class CommissionSettingActivity extends BaseActivity implements OnAdapterCallbackListener, SwipeRefreshLayout.OnRefreshListener
        , OnDataListener, AbsRecyclerViewAdapter.OnItemClickListener, SettingGroupDialog.OnSetGroupListener
        , AbsRecyclerViewAdapter.OnItemLongClickListener, CommissionSettingAdapter.OnLongListener, UpdateGroupDialog.OnModifyGroupListener {

    @BindView(R.id.toolbar_text)
    public Toolbar toolbar;
    @BindView(R.id.toolbar_next)
    public TextView tvNextBtn;
    @BindView(R.id.rv_group)
    public RecyclerView recyclerView;
    @BindView(R.id.srl)
    public SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_wechat_num)
    public TextView tvRabit;

    private String groupStr;

    private CommissionSettingAdapter recyclerViewAdapter;

    private Gson gson = new GsonBuilder().create();
    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 20;
    private String userId;
    private LoadingDialog loadingDialog;
    private List<vipsGroupsEntity.BodyBean> dataList = new ArrayList<>();
    RefreshtokenEntity refreshtoken;
    List<allVipMembersEntity.BodyBean> smList; //返回后所有组员要进行筛选进行增删改
    List<String> addMember = new ArrayList<>();


    //用于未添加组员时，不生成组
    AddGroupEntity addGroupEntity;


    @Override
    protected int getViewResId() {
        return R.layout.activity_commission_setting;
    }

    @Override
    protected void init() {
        userId = PreferencesUtil.getUserId(this);
        ToolBarUtil.initToolBar(toolbar, "分佣设置", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        }, "添加分组", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SettingGroupDialog dialog = SettingGroupDialog.newInstance(CommissionSettingActivity.this, null, 0);
                dialog.setListener(CommissionSettingActivity.this);
                dialog.show(getFragmentManager());
            }
        });
        tvNextBtn.setTextColor(getResources().getColor(R.color.red));


        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewAdapter = new CommissionSettingAdapter(this, this);
        recyclerViewAdapter.setOnItemClickListener(this);
        recyclerViewAdapter.setOnItemLongClickListener(this);
        recyclerViewAdapter.setOnLongListener(this);
        View footView = LayoutInflater.from(this).inflate(R.layout.item_text, null);
        recyclerViewAdapter.addFooterView(footView);
        recyclerView.setAdapter(recyclerViewAdapter);
//        recyclerView.addItemDecoration(new DividerGridItem(this, DividerGridItem.ATTRS));
/*        recyclerViewAdapter.setEmptyView(R.layout.empty_tips);
        recyclerViewAdapter.setEmptyTips(R.id.tv_emptyTips, getString(R.string.emptyAddress));*/
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);


        loadingDialog = LoadingDialog.newInstance("订单加载...");
        loadingDialog.show(getFragmentManager());
    }


    @Override
    protected void loadData() {
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map, this);
        getData();
    }


    private void getData() {
        Map<String, String> map = new HashMap<>();
        OkHttpUtil.getJSON(this, Constant.URL.vips_groups, map, this);
    }


    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.vips_groups.equals(url)) {
                LogeUtil.e("vips_groups", json);
                dismissLoading();

                vipsGroupsEntity recommendEntity = gson.fromJson(json, vipsGroupsEntity.class);
                dataList.clear();
                if ("200".equals(recommendEntity.getCode())) {
                    groupStr = gson.toJson(recommendEntity);
                    dataList.addAll(recommendEntity.getBody());
                }
                recyclerViewAdapter.setData(dataList);
            } else if (Constant.URL.refresh_token.equals(url)) { //刷新Token
                LogeUtil.e("refresh_token", json);
                dismissLoading();
                refreshtoken = gson.fromJson(json, RefreshtokenEntity.class);
                if (Constant.Strings.SUC.equals(refreshtoken.getCode())) {
                    //改变 主页bottom vip 图标及文字颜色
                    mRxManager.post(getResources().getString(R.string.ChangeMainBotton_vip_dirwableAndColor),refreshtoken.getBody().getMember().getType());

                    SharedPreferencesUtil.saveRoleInfo(this, json);
                    SharedPreferencesUtil.saveToken(this, refreshtoken.getBody().getToken());
                    tvRabit.setText("分佣比例" + refreshtoken.getBody().getMember().getDefaultBrokenPercent() + "%");
                } else {
                    ToastUtil.initToast(this, refreshtoken.getMsg());
                }
            } else if (Constant.URL.save_group.equals(url)) { //添加组成员
                dismissLoading();
                LogeUtil.e("save_group", json);
                feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                if (Constant.Strings.SUC.equals(fbe.getCode())) {
/*                    Intent intent = new Intent(CommissionSettingActivity.this, AddMemberActivity.class);
                    intent.putExtra("modleId", fbe.getBody().getModelId());
                    startActivityForResult(intent, Constant.Code.CommissionAddMember);*/
                    requestAddMember(fbe.getBody().getModelId(), null, null, addMember);
                } else {
                    ToastUtil.initToast(this, fbe.getMsg());
                }
            }
        }
    }

    private void addBaseLine() {
/*        if (pageIndex != 1) {
            dataList.add(new TransferRecoredEntity.DataBean.RowsBean(2));
        }*/
    }

    private void removeLoadingItem() {
/*        if (dataList != null) {
            if (dataList.size() > 0) {
                if (dataList.get(dataList.size() - 1).getType() == 1) {
                    dataList.remove(dataList.size() - 1);
                }
            }
        }*/
    }


    @Override
    public void onFailure(String url, String error) {

    }


    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

        if (swipeRefreshLayout != null && swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }

    }


    @OnClick({R.id.tv_add_group, R.id.ll_commission_layout})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_group: {
                startActivityForResult(new Intent(this, AddGroupsActivity.class).putExtra("entrance", 0), Constant.Code.AddGroupMember);
                break;
            }
            case R.id.ll_commission_layout: {
                startActivityForResult(new Intent(this, DefaultRatioActivity.class).putExtra("rabit", refreshtoken.getBody().getMember().getDefaultBrokenPercent()), Constant.Code.Rabit);
                break;
            }
        }
    }

    /**
     * 列表item点击事件
     *
     * @param v
     * @param position
     */
    @Override
    public void onItemClick(View v, int position) {
        switch (v.getId()) {
            case R.id.tv_expand_all: {
                dataList.get(position).getMembers().get(0).setExpand(!dataList.get(position).getMembers().get(0).isExpand());
//                recyclerViewAdapter.setExpand(position);
                recyclerViewAdapter.notifyDataSetChanged();
                break;
            }
            case R.id.tv_level2:
/*                startActivityForResult(new Intent(this, AddGroupsActivity.class).putExtra("entrance", 1)
                        .putExtra("nickName", dataList.get(position).getName())
                        .putExtra("percent", dataList.get(position).getBrokenPercent())
                        .putExtra("groudId", dataList.get(position).getId())
                        .putExtra("groupMember", gson.toJson(dataList.get(position).getMembers())), Constant.Code.AddGroupMember);*/
                SettingGroupDialog dialog = SettingGroupDialog.newInstance(CommissionSettingActivity.this, gson.toJson(dataList.get(position)), 1);
                dialog.setListener(this);
                dialog.show(getFragmentManager());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.Code.AddGroupMember) {
            if (resultCode == RESULT_OK) {
                onRefresh();
            }
        } else if (requestCode == Constant.Code.Rabit) {
            if (resultCode == RESULT_OK) {
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(this, Constant.URL.refresh_token, null, map, this);
            }
        } else if (requestCode == Constant.Code.CommissionAddMember) {
            if (resultCode == RESULT_OK) {
                String json = data.getStringExtra("entity");
                smList = gson.fromJson(json, new TypeToken<List<allVipMembersEntity.BodyBean>>() {
                }.getType());
                addMember.clear();
                for (allVipMembersEntity.BodyBean bean : smList) {
                    addMember.add(bean.getId());
                }
                requestAddMember(data.getStringExtra("modleId"), null, null, addMember);
            } else {
                loadData();
            }
        } else if (requestCode == Constant.Code.CommissionAddGroup) {
            if (resultCode == RESULT_OK) {
                String json = data.getStringExtra("entity");
                smList = gson.fromJson(json, new TypeToken<List<allVipMembersEntity.BodyBean>>() {
                }.getType());
                addMember.clear();
                for (allVipMembersEntity.BodyBean bean : smList) {
                    addMember.add(bean.getId());
                }

                /**
                 * 返回先创建组
                 */
                if (addGroupEntity != null) {
                    loadingDialog = LoadingDialog.newInstance("提交中...");
                    loadingDialog.show(getFragmentManager());
                    Map<String, Object> map = new HashMap<>();
                    if (addGroupEntity.getStatus() == 0) { //说明是添加新的组
                        OkHttpUtil.postJson(this, Constant.URL.save_group, new SaveGroup(addGroupEntity.getId(), addGroupEntity.getGroupName(), addGroupEntity.getGroupRabit(), addMember), map, this);

                    } else { //说明是编辑原来的组
                        OkHttpUtil.postJson(this, Constant.URL.save_group, new SaveGroup(addGroupEntity.getId(), addGroupEntity.getGroupName(), addGroupEntity.getGroupRabit(), addMember), map, this);
                    }

                }
            } else {
                loadData();
            }
        }

    }


    //设置分组对话框接口回调
    @Override
    public void crateGroup(String groupName, String groupRabit, int status, String id) {
        addGroupEntity = new AddGroupEntity(groupName, groupRabit, id, status);
        if (status != 0) { //说明是编辑原来的组
            loadingDialog = LoadingDialog.newInstance("提交中...");
            loadingDialog.show(getFragmentManager());
            Map<String, Object> map = new HashMap<>();
            OkHttpUtil.postJson(this, Constant.URL.save_group, new SaveGroup(id, groupName, groupRabit, null), map, new OnDataListener() {
                @Override
                public void onResponse(String url, String json) {
                    if (!TextUtils.isEmpty(json)) {
                        if (Constant.URL.save_group.equals(url)) { //添加组成员
                            dismissLoading();
                            LogeUtil.e("save_group", json);
                            feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                            if (Constant.Strings.SUC.equals(fbe.getCode())) {
//                                Intent intent = new Intent(CommissionSettingActivity.this, AddMemberActivity.class);
////                                intent.putExtra("modleId", fbe.getBody().getModelId());
////                                startActivityForResult(intent, Constant.Code.CommissionAddMember);
                                loadData();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(String url, String error) {

                }
            });
        } else {
            Intent intent = new Intent(CommissionSettingActivity.this, AddMemberActivity.class);
            intent.putExtra("modleId", "default");
            startActivityForResult(intent, Constant.Code.CommissionAddGroup);
        }

    }

    /**
     * 添加组员成功，并刷新
     *
     * @param id
     * @param name
     * @param broker
     * @param list
     */
    private void requestAddMember(String id, String name, String broker, List<String> list) {
        loadingDialog = LoadingDialog.newInstance("提交中...");
        loadingDialog.show(getFragmentManager());
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.save_group, new SaveGroup(id, name, broker, list), map, new OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                if (!TextUtils.isEmpty(json)) {
                    if (Constant.URL.save_group.equals(url)) { //添加组成员
                        dismissLoading();
                        LogeUtil.e("save_members", json);
                        feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                        if (Constant.Strings.SUC.equals(fbe.getCode())) {
                            loadData();
                        }
                    }
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    public void delGroup(String id, String name, String broker, List<String> list) {
        loadingDialog = LoadingDialog.newInstance("提交中...");
        loadingDialog.show(getFragmentManager());
        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.remove_group, new SaveGroup(id, name, broker, list), map, new OnDataListener() {
            @Override
            public void onResponse(String url, String json) {
                if (!TextUtils.isEmpty(json)) {
                    if (Constant.URL.remove_group.equals(url)) { //添加组成员
                        dismissLoading();
                        LogeUtil.e("remove_group", json);
                        feedbackEntity fbe = gson.fromJson(json, feedbackEntity.class);
                        if (Constant.Strings.SUC.equals(fbe.getCode())) {
                            loadData();
                        }
                    }
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    //长按监听
    @Override
    public boolean onItemLongClick(View v, final int position) {
        if (dataList.get(position).getMembers().size() <= 0) {
            ConfirmDialog dialog = ConfirmDialog.newInstance("是否确认删除该分组？", "取消", "确定");
            dialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                @Override
                public void onItemClick(View v) {
                    switch (v.getId()) {
                        case R.id.btn_confirmDialog: {
                            delGroup(dataList.get(position).getId(), dataList.get(position).getName(), dataList.get(position).getBrokenPercent(), null);
                        }
                        break;
                    }
                }
            });
            dialog.show(getFragmentManager());
        }
        return false;
    }

    @Override
    public void onLongClick(final int position) {
        if (dataList.get(position).getMembers().size() <= 0) {
            ConfirmDialog dialog = ConfirmDialog.newInstance("是否确认删除该分组？", "取消", "确定");
            dialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                @Override
                public void onItemClick(View v) {
                    switch (v.getId()) {
                        case R.id.btn_confirmDialog: {
                            delGroup(dataList.get(position).getId(), dataList.get(position).getName(), dataList.get(position).getBrokenPercent(), null);
                        }
                        break;
                    }
                }
            });
            dialog.show(getFragmentManager());
        }
    }

    @Override
    public void onChildrenHead(int poition, int childPostion) {
        if (!TextUtils.isEmpty(groupStr)) {
            UpdateGroupDialog dialog = UpdateGroupDialog.newInstance(this, dataList.get(poition).getId(), dataList.get(poition).getMembers().get(childPostion).getNickName(), dataList.get(poition).getMembers().get(childPostion).getId(), groupStr);
            dialog.setOnModifyGroupListener(this);
            dialog.show(getFragmentManager());
        }
    }

    @Override
    public void onAddMember(int poition) {
        Intent intent = new Intent(CommissionSettingActivity.this, AddMemberActivity.class);
        intent.putExtra("modleId", dataList.get(poition).getId());
        startActivityForResult(intent, Constant.Code.CommissionAddMember);
    }

    @Override
    public void modifyGroup(String groupId, String memberId) {
        List<String> mList = new ArrayList<>();
        mList.add(memberId);
        requestAddMember(groupId, null, null, mList);
    }
}
